// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const qrMd5 = event.scene;
  //查询WiFi信息
  let res = await db.collection('md5_index').where({
    qrMd5
  }).get();

  //获取当前时间
  function format(val) {
    return val < 10 ? `0${val}` : val
  }
  let myDate = new Date();
  let year = format(myDate.getFullYear()); //获取当前年
  let mon = format(myDate.getMonth() + 1); //获取当前月
  let date = format(myDate.getDate()); //获取当前日
  let hours = format(myDate.getHours()); //获取当前小时
  let minutes = format(myDate.getMinutes()); //获取当前分钟
  let seconds = format(myDate.getSeconds()); //获取当前秒
  let now = `${year}年${mon}月${date}日 ${hours}:${minutes}:${seconds}`;
  //将次数和时间更新到数据库
  db.collection('md5_index').doc(res.data[0]._id).update({
    data: {
      time: _.inc(1),
      lastDate: now
    },
  })
  return res
}